package com.gjs.freechat.web.business;

import java.nio.channels.SeekableByteChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

import javax.websocket.CloseReason;
import javax.websocket.Session;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.gjs.freechat.server.business.ChatSessionBusiness;
import com.gjs.freechat.server.component.bean.Conversation;
import com.gjs.freechat.server.component.bean.Message;
import com.gjs.freechat.server.component.bean.UserInfo;
import com.gjs.freechat.web.constant.WebConstants;
import com.gjs.freechat.web.controller.UserConnectionWebSocket;


@Component
public class WebUserConnectionPool {
	
	private static Logger logger = Logger.getLogger(WebUserConnectionPool.class);
	
	@Autowired
	WebChatSessionManage webChatSessionManage;
	
	@Autowired
	private ChatSessionBusiness chatSessionBusiness;
	
	private Map<String, List<Object>> userConnectionPool;
	
	public WebUserConnectionPool() {
		userConnectionPool = new ConcurrentHashMap<String, List<Object>>();
		UserConnectionWebSocket.connPool = this;
	}
	
	public void addNewUserConnection(String connId, String userId, Object connSocket) {
		logger.info("新的用户连接建立,userId:" + userId + ",connectionId" + connId);
		List<Object> connSockets = userConnectionPool.get(userId);
		if (connSockets == null) {
			connSockets = Collections.synchronizedList(new LinkedList<Object>());
		}
		connSockets.add(connSocket);
		userConnectionPool.put(userId, connSockets);
		logger.info("当前总共的连接数:" + userConnectionPool.size());
	}
	
	public void onMessage(String jsonMsg, String userId) {
		Message msg = JSON.parseObject(jsonMsg, Message.class);
		chatSessionBusiness.sendTextMessage(msg);
	}
	
	public boolean sendMessage(Message message) {
		List<Object> connSockets = userConnectionPool.get(message.getReceiverId());
		if (connSockets != null && connSockets.size() != 0) {
			for (Object soc : connSockets) {
				Session socket = (Session) soc;
				if (socket.isOpen()) {
					socket.getAsyncRemote().sendText(JSON.toJSONString(message));
				}
			}
		}
		return false;
	}
	
	public void sendMessages(Message msg, List<Conversation> convos) {
		for (int i = 0; i < convos.size(); i++) {
			if (convos.get(i).getPartner() == null || convos.get(i).getPartnerStatus() == UserInfo.USER_STATUS_OFFLINE)
				continue;
			msg.setReceiverId(convos.get(i).getPartnerId());
			msg.setSessionId(convos.get(i).getId());
			sendMessage(msg);
		}
	}
	
	public void removeConnection(CloseReason closeReason, Session session, String userId) {
		List<Object> socs = userConnectionPool.get(userId);
		socs.remove(session);
		if (closeReason.getCloseCode().getCode() == 1001) {   //如果是闭关浏览器
			
		}
	}
	
	public List<Object> findUsersConnctionSockets(List<String> userIds) {
		List<Object> connSockets = new ArrayList<Object>(userIds.size());
		for (int i = 0; i < userIds.size(); i++) {
			List<Object> socs = userConnectionPool.get(userIds.get(i));
			if (socs == null) 
				continue;
			//Map<String, Object> userSocs = new HashMap<String, Object>();
			//userSocs.put("userId", userIds.get(i));
			//userSocs.put("connSockets", socs);
			connSockets.addAll(socs);
		}
		return connSockets;
		
	}
	
	public List<Object> findUserConnectionSockets(String userId) {
//		List<Map<String, Object>> connSockets = new ArrayList<Map<String,Object>>();
//		for (Entry<String, Map<String, Object>> conn : userConnectionPool.entrySet()) {
//			if (conn.getValue().get("userId").equals(userId)) {
//				connSockets.add(conn.getValue());
//			}
//		}
		List<Object> connSockets = userConnectionPool.get(userId);
		
		return connSockets;
	}
	
	
}
